import axios from 'axios'
import {ElMessage,ElLoading} from "element-plus"
const instance = axios.create({    //创建axios实例，在这里可以设置请求的默认配置
    timeout: 1000 * 30, // 设置超时时间10s
    baseURL: '/',   //根据自己配置的反向代理去设置不同环境的baeUrl
})
instance.defaults.headers.post['Content-Type'] = 'application/json';
instance.interceptors.request.use(config=>{
    return config
},error => {
    return Promise.reject(error)
})
instance.interceptors.response.use(response =>{
    return Promise.resolve(response.data)
},error => {
    return Promise.reject(error)
})
export const get = (url, params, config = {}) => {
    const  loadState = ElLoading.service({});
    return new Promise((resolve, reject) => {
        instance({
            method: 'get',
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
            loadState.close();
        }).catch(error => {
            console.log(error)
            loadState.close();
            if(error.request.status == 404){
                ElMessage.error({
                    showClose: true,
                    message: '数据加载失败',
                    type: 'success'
                })
            }
            reject(error)
        })
    })
}
export const post = (url, data, config = {}) => {
    const  loadState = ElLoading.service({});
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            loadState.close();
            if(error.request.status == 404){
                ElMessage.error({
                    showClose: true,
                    message: '数据加载失败',
                    type: 'success'
                })
            }
            reject(error)
        })
    })
}

export const axiosInstance = instance;

